package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.service.LoanDataUpdateService;
import org.example.service.LoanDataUpdateService.UpdateResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 贷款数据更新控制器
 * 用于更新放款时间和还款计划
 */
@Slf4j
@RestController
@RequestMapping("/loan/update")
public class LoanDataUpdateController {

    private static final Logger log = LoggerFactory.getLogger(LoanDataUpdateController.class);

    @Autowired
    private LoanDataUpdateService loanDataUpdateService;

    /**
     * 更新放款时间从2024-07改为2025-01
     */
    @PostMapping("/loanTime")
    public Map<String, Object> updateLoanTime() {
        log.info("开始更新放款时间");

        try {
            UpdateResult result = loanDataUpdateService.updateLoanTimeAndRepayPlan();

            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            response.put("userInfoUpdated", result.getUserInfoUpdated());
            response.put("repayPlanUpdated", result.getRepayPlanUpdated());
            response.put("duration", result.getDuration() + "ms");

            return response;
        } catch (Exception e) {
            log.error("更新放款时间失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 按日期范围更新放款时间
     * @param oldStartDate 原开始日期，如 "2024-07-19"
     * @param oldEndDate 原结束日期，如 "2024-07-31"
     * @param newStartDate 新开始日期，如 "2025-01-02"
     */
    @PostMapping("/loanTimeByRange")
    public Map<String, Object> updateLoanTimeByRange(
            @RequestParam String oldStartDate,
            @RequestParam String oldEndDate,
            @RequestParam String newStartDate) {
        
        log.info("按日期范围更新放款时间: {} ~ {} -> {}", oldStartDate, oldEndDate, newStartDate);

        try {
            UpdateResult result = loanDataUpdateService.updateLoanTimeByDateRange(
                oldStartDate, oldEndDate, newStartDate);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            response.put("userInfoUpdated", result.getUserInfoUpdated());
            response.put("repayPlanUpdated", result.getRepayPlanUpdated());
            response.put("duration", result.getDuration() + "ms");

            return response;
        } catch (Exception e) {
            log.error("更新放款时间失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 批量修改放款时间（支持多个月份映射）
     * @param mappings 月份映射JSON，格式：{"2025-09": "2024-10", "2024-10": "2024-12"}
     */
    @PostMapping("/batchUpdateByMapping")
    public Map<String, Object> batchUpdateByMapping() {
        log.info("批量修改放款时间（性能优化版）");

        try {
            UpdateResult result = loanDataUpdateService.batchUpdateLoanTimeByMonthMapping();

            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            response.put("userInfoUpdated", result.getUserInfoUpdated());
            response.put("repayPlanUpdated", result.getRepayPlanUpdated());
            response.put("duration", result.getDuration() + "ms");
            response.put("speedPerSecond", (result.getUserInfoUpdated() + result.getRepayPlanUpdated()) * 1000 / Math.max(result.getDuration(), 1));

            return response;
        } catch (Exception e) {
            log.error("批量更新失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量更新失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取服务说明
     */
    @GetMapping("/info")
    public Map<String, Object> getInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("description", "贷款数据更新服务");

        Map<String, String> apis = new HashMap<>();
        apis.put("更新放款时间(2024-07->2025-01)", "POST /loan/update/loanTime");
        apis.put("按日期范围更新", "POST /loan/update/loanTimeByRange?oldStartDate=2024-07-19&oldEndDate=2024-07-31&newStartDate=2025-01-02");
        apis.put("批量月份映射更新", "POST /loan/update/batchUpdateByMapping (Body: {\"2025-09\": \"2024-10\", \"2024-10\": \"2024-12\"})");

        response.put("apis", apis);

        Map<String, String> rules = new HashMap<>();
        rules.put("用户信息更新", "将 loan_time 从 2024-07-xx 改为 2025-01-xx，保留时分秒");
        rules.put("还款计划更新", "due_time = 新放款时间 + 期数(月)");
        rules.put("正常还款", "actual_repay_time = due_time (repay_status=2)");
        rules.put("逾期还款", "actual_repay_time = due_time + overdue_days (repay_status=3)");

        response.put("updateRules", rules);

        return response;
    }
}

